/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.lock;

import com.inspur.edp.bef.api.be.BefLockType;
import com.inspur.edp.bef.api.be.IBEContext;
import com.inspur.edp.bef.api.be.IBusinessEntity;
import com.inspur.edp.bef.api.exceptions.BizMessageException;
import com.inspur.edp.bef.api.exceptions.DataVersionMismatchException;
import com.inspur.edp.bef.api.exceptions.ErrorCodes;
import com.inspur.edp.bef.core.DotNetToJavaStringHelper;
import com.inspur.edp.bef.core.be.BEContext;
import com.inspur.edp.bef.core.scope.BefScope;
import com.inspur.edp.bef.spi.entity.builtinimpls.BefModelResInfoImpl;
import com.inspur.edp.cef.api.RefObject;
import com.inspur.edp.cef.api.message.BizMessage;
import com.inspur.edp.cef.api.message.MessageLevel;
import com.inspur.edp.cef.api.message.MessageLocation;
import com.inspur.edp.cef.core.i18n.I18nResourceUtil;
import com.inspur.edp.cef.spi.entity.resourceInfo.ModelResInfo;
import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.core.session.SessionType;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import lombok.var;
import org.springframework.util.StringUtils;

public class LockUtils
{
	private LockUtils(){}

//	public final static List<IBusinessEntity> addLock(List<IBusinessEntity> beList) {
//		BefScope scope = new BefScope();
//		scope.beginScope();
//		try
//		{
//			for (IBusinessEntity be : beList)
//			{
//				be.addLockWithScope();
//			}
//			scope.setComplete();
//
//			//返回加锁成功的BizEntities列表
//			return getAddLockResult(beList);
//		}
//		catch (java.lang.Exception e)
//		{
//			scope.setAbort();
//			throw new RuntimeException(e);
//		}
//
//	}
//
//	private static List<IBusinessEntity> getAddLockResult(List<IBusinessEntity> beList)
//	{
//		return beList.stream().filter(item -> item.getBEContext().isLocked()).collect(Collectors.toList());
//	}

	//产生修改的BEAction执行时检查加锁状态, 加锁一般是在MgrAction中进行, BEAction执行时也要再检查一遍因为有可能自定义MgrAction没检查直接调进来的
	public static void checkLock(IBEContext beContext) {
		if (beContext.isNew() || beContext.isLocked())
		{
			return;
		}
		if(!needLock(beContext.getModelResInfo()))
			return;

		LockService.getInstance().addLock(beContext.getBizEntity().getBEType(), beContext.getID());
		checkLocked(beContext);
		//TODO: dal暂不支持检查版本. 加锁之后检查版本, 如果版本不一致抛异常
	}

	public static void checkLocked(IBEContext beContext) {
		if(!needLock(beContext.getModelResInfo()))
			return;
		RefObject<String> userName= new RefObject("");
		if (((BEContext)beContext).isLocked(userName))
			return;

		//TODO: 使用统一的消息机制
		throwLockFailed(Arrays.asList(beContext.getID()), userName.argvalue);
	}

	public static boolean needLock(ModelResInfo resInfo) {
		if(resInfo instanceof BefModelResInfoImpl
				&& ((BefModelResInfoImpl)resInfo).getLockType()== BefLockType.None)
			return false;
		return true;
	}


	public static void throwLockFailed(List<String> ids, String userName)
	{
		//String language=CAFContext.current.getLanguage();
		BizMessage tempVar = new BizMessage();
		String lockMessage1=I18nResourceUtil.getResourceItemValue("pfcommon","cef_exception.properties","Gsp_Bef_LockVal_0001");
		String lockMessage2=I18nResourceUtil.getResourceItemValue("pfcommon","cef_exception.properties","Gsp_Bef_LockVal_0002");
		String lockMessage3=I18nResourceUtil.getResourceItemValue("pfcommon","cef_exception.properties","Gsp_Bef_LockVal_0003");
		if(StringUtils.isEmpty(userName)){
			tempVar.setMessageFormat(lockMessage1);
		}else{
			tempVar.setMessageFormat(lockMessage2+userName+" "+lockMessage3);
		}
//		tempVar.setMessageFormat(DotNetToJavaStringHelper.isNullOrEmpty(userName) ? "数据已被其他用户锁定，无法执行当前操作" :"数据已被 "+userName+" 锁定，无法执行当前操作");
		MessageLocation location = new MessageLocation();
		location.setDataIds(ids);
		tempVar.setLocation(location);
		tempVar.setLevel(MessageLevel.Error);
		throw new BizMessageException(ErrorCodes.EditingLocked, tempVar);
	}
}
